<?php

//返回随机字符串
function random_str($length = 16) {
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $key = '';
    for($i = 0; $i < $length; $i++)
    {
        $key .= $pattern[mt_rand(0,35)];    //生成php随机数
    }
    return $key;
}

//xml数据转化成数组
if (!function_exists('xml2arr')) {
    /**
     * @param $xml_str
     * @return array
     */
    function xml2arr($xml_str)
    {
        $str = '';
        $new_arr = [];
        $xml_obj = simplexml_load_string($xml_str);
        //拼接成a=1&b=2形式字符串
        foreach ($xml_obj->children() as $child) {
            $str .= $child->getName() . '=' . $child . '&';
        }
        //去掉最后一位的&字符
        $str = substr($str,0,-1);
        $arr = explode('&',$str);

        foreach($arr as $value){
            $tmp = explode('=',$value);
            if($tmp[1]){//只返回有值的key
                $new_arr[$tmp[0]] = $tmp[1];
            }
        }
        return $new_arr;
    }
}

function arr2xml($data, $root = true){
    $str="";
    if($root)$str .= "<xml>";
    foreach($data as $key => $val){
        //去掉key中的下标[]
        $key = preg_replace('/\[\d*\]/', '', $key);
        if(is_array($val)){
            $child = arr2xml($val, false);
            $str .= "<$key>$child</$key>";
        }else{
            $str.= "<$key><![CDATA[$val]]></$key>";
        }
    }
    if($root)$str .= "</xml>";
    return $str;
}
